<?php
namespace app\jiyun\controller\cargo;

use app\common\model\admin\service_config\ServiceConfigTabAccount;
use app\common\model\collect\OrderExpressGoodsModel;
use app\common\model\collect\OrderExpressModel;
use app\common\model\jiyun\base\ChannelModel;
use app\common\model\jiyun\OrderModel;
use app\common\model\jiyun\warehouse\WarehouseModel;
use app\common\model\jiyun\warehouse\WarehouseRegionLocationModel;
use app\jiyun\service\base\CommonService;
use think\admin\Controller;
use think\facade\Db;
use think\facade\Validate;

/**
 * 包裹合箱
 * @Description
 * @package app\jiyun\controller\cargo
 * @author xuli
 * @date 2024-12-04 10:22
 */
class packageCombine extends Controller
{
    /**
     * 包裹合箱
     * @auth true
     * @menu true
     */
    public function index()
    {
        $this->fetch();
    }

    /**
     * 获取商品列表
     * @return \think\response\Json
     */
    public function getGoodsList()
    {
        $params = $this->request->param();
        $where = [];
        if(!empty($params['express_no'])) {
            $where[] = ['express_no', '=', $params['express_no']];

            $where[] = ['oe.pid', '=', 0];
            $where[] = ['oe.status', '=', OrderExpressModel::STATUS_IN_STORE];
            $info = OrderExpressModel::mq()->alias('oe')->field('oe.*,jo.status jiyun_status')
                ->join('jiyun_order jo', 'jo.id = oe.jiyun_order_id')
                ->where($where)->find();
            if(empty($info)) {
                $this->error('包裹不存在');
            }
            if($info['status'] < OrderExpressModel::STATUS_IN_STORE) {
                $this->error('包裹未入库');
            }
            if($info['jiyun_status'] == OrderExpressModel::STATUS_IN_STORE) {
                $this->error('集运单下的包裹还没有全部入库，不能合箱');
            }
            $this->success('', $info['jiyun_order_id']);
        }

        if(empty($params['jiyun_order_id'])) {
            return json(['code' => 0, 'data' => [], 'info' => '商品列表']);
        }

        if(!$this->super){
            $this->check_user = true;
        }

        $where[] = ['pid', '=', 0];
        $where[] = ['jiyun_order_id', '=', $params['jiyun_order_id']];
        $where[] = ['status', '=', OrderExpressModel::STATUS_IN_STORE];
        $list = OrderExpressModel::mq()->where($where)->select()->toArray();

        $common_service   = CommonService::instance();
        // 获得仓库
        $warehouse_arr    = $common_service->getWarehouse($this->account_id);
        // 获得平台
        $system_platform  = $common_service->getSystemPlatform();
        // 获得公司名字
        $account          = $common_service->getAccount();

        foreach ($list as &$item) {
            $item['warehouse_name'] = $warehouse_arr[$item['warehouse_id']] ?? '';
            $item['account_name']   = $account[$item['account_id']]  ?? '';
            $item['status_name']    = OrderExpressModel::getStatus()[$item['status']] ?? '';
        }

        return json(['code' => 0, 'data' => $list, 'info' => '商品列表']);
    }

    /**
     * 确认合箱
     * @return void
     */
    public function CombinePacking()
    {
        $params = $this->request->post();
        if(empty($params['packing_ids'])) {
            $this->error(lang('请选择要操作的数据'));
        }

        // 获取操作的数据
        $list = OrderExpressModel::mq()->where(['is_merge' => 0])
            //->where('status', '=', OrderExpressModel::STATUS_IN_STORE)
            ->whereIn('id', $params['packing_ids'])->select()->toArray();

        if(count($list) <= 1) {
            $this->error(lang('合箱数据必须大于等于2条'));
        }

        $info = [];
        $packing_ids = [];
        foreach ($list as $item) {
            if($item['status'] != 2) {
                $this->error('包裹状态错误');
            }
            $info = $item;
            $packing_ids[] = $item['id'];
        }

        // 生成新的商品信息
        $data = [
            'from' => 1,
            'shop_account_id' => $info['shop_account_id'] ?? 0,
            //'platform_id' => $info['platform_id'] ?? 0,
            'account_id' => $info['account_id'] ?? 0,
            'warehouse_id' => $info['warehouse_id'] ?? 0,
            'jiyun_order_id' => $info['jiyun_order_id'] ?? 0,
            'order_no' => $info['order_no'] ?? '',
            'express_company' => '', // 物流公司
            'express_no' => OrderExpressModel::createCombineNo(), // 合箱单号
            'is_merge' => 1,
            'status' => OrderExpressModel::STATUS_IN_STORE,
        ];

        // 启动事务
        Db::startTrans();
        try {
            $combine_id = OrderExpressModel::mq()->insertGetId($data);

            // 更新合箱商品的状态
            $result = OrderExpressModel::mq()->whereIn('id', $packing_ids)->update(['pid' => $combine_id]);
            if(!$result) {
                throw new \Exception('数据保存失败');
            }
            Db::commit();
        } catch (\Exception $e) {
            Db::rollback();
            $this->error(lang('合箱失败') . '：' . $e->getMessage());
        }

        $this->success(lang('合箱成功'));
    }
}